/**
 * Create Axios
 * 请求接口
 */

import axios from 'axios';
import Vue from 'vue'
export const http = axios.create();

/**
 * We'll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the "XSRF" token cookie.
 */
http.defaults.headers.common = {
    'X-Requested-With': 'XMLHttpRequest'
};

http.interceptors.request.use(function (config) {
    console.log(config,'==success==request==')
    if (config.method === 'post') {
        if (!config.data) {
            config.data = {};
        }
    } else if(config.method === 'get') {
        if (!config.params) {
            config.params = {};
        }
    }
    return config;
}, function (error) {
    return Promise.reject(error);
});

/**
 * Handle all error messages.
 */
http.interceptors.response.use(function (response) {
    console.log(response,'==success==response==')
    return response;
}, function (error) {
    const { response } = error;

    if ([401].indexOf(response.status) >= 0) {
        if (response.status === 401 && response.data.error.message !== 'Unauthorized') {
            return Promise.reject(response);
        }
    }

    return Promise.reject(error);
});

export default function install(Vue) {
    Object.defineProperty(Vue.prototype, '$http', {
        get() {
            return http
        }
    })
}

